package handlers

import (
	"net/http"
	"strconv"

	"minipromgr/internal/models"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// GetProjects 获取所有项目（用于Dashboard）
func GetProjects(c *gin.Context) {
	db := models.GetDB()
	var projects []models.Project
	// 只获取active状态的项目，过滤掉archived项目
	if err := db.Where("status = ?", models.ProjectStatusActive).Find(&projects).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch projects"})
		return
	}

	// 为每个项目添加统计信息
	var projectsWithStats []gin.H
	for _, project := range projects {
		var taskCount, issueCount, requirementCount int64

		db.Model(&models.Item{}).Where("project_id = ? AND type = ?", project.ID, models.TypeTask).Count(&taskCount)
		db.Model(&models.Item{}).Where("project_id = ? AND type = ?", project.ID, models.TypeIssue).Count(&issueCount)
		db.Model(&models.Item{}).Where("project_id = ? AND type = ?", project.ID, models.TypeRequirement).Count(&requirementCount)

		projectsWithStats = append(projectsWithStats, gin.H{
			"id":                project.ID,
			"name":              project.Name,
			"description":       project.Description,
			"created_at":        project.CreatedAt,
			"task_count":        taskCount,
			"issue_count":       issueCount,
			"requirement_count": requirementCount,
		})
	}

	c.JSON(http.StatusOK, gin.H{"projects": projectsWithStats})
}

// CreateProject 创建新项目
func CreateProject(c *gin.Context) {
	var project models.Project
	if err := c.ShouldBindJSON(&project); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	db := models.GetDB()
	if err := db.Create(&project).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create project"})
		return
	}

	c.JSON(http.StatusCreated, gin.H{"project": project})
}

// GetProject 获取单个项目详情
func GetProject(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid project ID"})
		return
	}

	db := models.GetDB()
	var project models.Project
	if err := db.First(&project, uint(id)).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			c.JSON(http.StatusNotFound, gin.H{"error": "Project not found"})
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch project"})
		}
		return
	}

	c.JSON(http.StatusOK, gin.H{"project": project})
}

// UpdateProject 更新项目
func UpdateProject(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid project ID"})
		return
	}

	var updateData models.Project
	if err := c.ShouldBindJSON(&updateData); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	db := models.GetDB()
	var project models.Project
	if err := db.First(&project, uint(id)).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			c.JSON(http.StatusNotFound, gin.H{"error": "Project not found"})
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch project"})
		}
		return
	}

	if err := db.Model(&project).Updates(updateData).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update project"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"project": project})
}

// DeleteProject 删除项目
func DeleteProject(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid project ID"})
		return
	}

	db := models.GetDB()
	if err := db.Delete(&models.Project{}, uint(id)).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete project"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Project deleted successfully"})
}

// ArchiveProject 归档项目
func ArchiveProject(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid project ID"})
		return
	}

	db := models.GetDB()
	var project models.Project
	if err := db.First(&project, uint(id)).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			c.JSON(http.StatusNotFound, gin.H{"error": "Project not found"})
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch project"})
		}
		return
	}

	// 更新项目状态为archived
	if err := db.Model(&project).Update("status", models.ProjectStatusArchived).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to archive project"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Project archived successfully"})
}
